package com.example.newland.co2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.media.session.MediaSession;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.HttpRetryException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private SharedPreferences config;
    private String tonken;
    private AlertDialog.Builder builder;
    private View inflate;
    private EditText dialog_username;
    private EditText dialog_pwd;
    private Button dialog_denglu;
    private ImageView dialog_setting;
    private String ip;
    private String port;
    private String username_str;
    private String pws_str;
    private TextView main_tv_shezhi;
    private TextView main_tv_zhuxiao;
    private Button main_but_open;
    private Button main_but_close;
    private TextView main_tx_zhi;
    private ImageView main_iv_fengshan;
    private Switch main_sw_kaiguan;
    private AlertDialog dialog;
    private boolean main_flag = false;

    private String setting_ed_shangxian;
    private String setting_ed_ch4;
    private String setting_ed_lora;
    private String setting_ed_port;
    private String setting_ed_ip;
    private String setting_ed_fans;
    private String setting_ed_wangguan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        main_tv_shezhi = findViewById(R.id.main_tv_shezhi);
        main_tv_zhuxiao = findViewById(R.id.main_tv_zhuxiao);
        main_but_open = findViewById(R.id.main_but_open);
        main_but_close = findViewById(R.id.main_but_close);
        main_tx_zhi = findViewById(R.id.main_tx_zhi);
        main_iv_fengshan = findViewById(R.id.main_iv_fengshan);
        main_sw_kaiguan = findViewById(R.id.main_sw_kaiguan);

        config = getSharedPreferences("config", MODE_PRIVATE);
        tonken = config.getString(XindaluConfig.Tonken, "");

        main_tv_shezhi.setOnClickListener(this);
        main_tv_zhuxiao.setOnClickListener(this);
        main_but_open.setOnClickListener(this);
        main_but_close.setOnClickListener(this);
        main_tx_zhi.setOnClickListener(this);
        main_iv_fengshan.setOnClickListener(this);
        main_sw_kaiguan.setOnCheckedChangeListener(this);

        if ("".equals(tonken) || tonken == null) {
            //未登录，弹框

            tankuang();

        } else {
            //登录，拉去数据

            shuju();
        }
    }

    private void shuju() {
        //数据
        Thread thread = new Thread() {

            @Override
            public void run() {
                while (true) {
                    if(main_flag) {


                        try {
                            //拉取数据
                            tonken = config.getString(XindaluConfig.Tonken, "");
                            setting_ed_ip = config.getString(XindaluConfig.setting_ed_ip, "");
                            setting_ed_port = config.getString(XindaluConfig.setting_ed_port, "");
                            setting_ed_lora = config.getString(XindaluConfig.setting_ed_lora, "");
                            setting_ed_ch4 = config.getString(XindaluConfig.setting_ed_ch4, "");
                            setting_ed_shangxian = config.getString(XindaluConfig.setting_ed_shangxian, "");
                            setting_ed_wangguan = config.getString(XindaluConfig.setting_ed_wangguan, "");
                            setting_ed_fans = config.getString(XindaluConfig.setting_ed_fans, "");

                            String jaiwan_url = "http://" + setting_ed_ip + ":" + setting_ed_port + "/devices/" + setting_ed_lora + "/Datas?deviceId=" + setting_ed_lora + "&ApiTags=" + setting_ed_ch4;
                            Log.i("甲烷数据url", jaiwan_url);
                            String resJSONstr = HttpMethodUtil.doGet(jaiwan_url, tonken);
                            //打印
                            Log.i("获取到的甲烷数据", resJSONstr);

                            JSONObject jsonObject = new JSONObject(resJSONstr);
                            int status = jsonObject.getInt("Status");

                            if (status == 0) {

                                //json解析
                                JSONObject resultObj = jsonObject.getJSONObject("ResultObj");
                                JSONArray dataPoints = resultObj.getJSONArray("DataPoints");
                                JSONObject datapoint = dataPoints.getJSONObject(0);
                                JSONArray pointDTO = datapoint.getJSONArray("PointDTO");
                                JSONObject pointDTOs = pointDTO.getJSONObject(0);
                                String value = pointDTOs.getString("Value");

                                Message message = new Message();
                                message.what = 1;

                                Bundle bundle = new Bundle();
                                bundle.putString("value", value);
                                message.setData(bundle);

                                handler.sendMessage(message);


                                Double value_double = Double.valueOf(value);
                                Double jiawan_double = Double.valueOf(setting_ed_shangxian);

                                if(value_double > jiawan_double){
                                    //开风扇
                                    String fs_url = "http://"+ setting_ed_ip +":"+ setting_ed_port +"/Cmds?deviceId="+setting_ed_wangguan+"&apiTag="+setting_ed_fans;
                                    Log.e("风扇url",fs_url);
                                    String fans_res = HttpMethodUtil.doPost(fs_url, "1", tonken);
                                    Log.e("调用风扇接口信息",fans_res);
                                    main_sw_kaiguan.setChecked(true);

                                }else{
                                    //关风扇
                                    String fs_url = "http://"+ setting_ed_ip +":"+ setting_ed_port +"/Cmds?deviceId="+setting_ed_wangguan+"&apiTag="+setting_ed_fans;
                                    Log.e("风扇url",fs_url);
                                    String fans_res = HttpMethodUtil.doPost(fs_url, "0", tonken);
                                    Log.e("调用风扇接口信息",fans_res);
                                    main_sw_kaiguan.setChecked(false);
                                }

                                Log.e("甲烷请求正确", "正确");
                            } else {
                                Log.e("甲烷请求错误", "错误");
                            }

                            Thread.sleep(5000);
                        } catch (Exception e) {
                            Log.e("json", "json解析错误");
                        }
                    }
                }
            }
        };
        thread.start();
    }

    private void tankuang() {
        //弹框
        //建造器
        builder = new AlertDialog.Builder(MainActivity.this);

        //加载布局
        inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_login, null);
        //弹框和界面绑定
        builder.setView(inflate);
        //点击别的地方，弹框会不会消失
        builder.setCancelable(false);
        //显示
        dialog = builder.show();

        //找到控件id
        dialog_username = inflate.findViewById(R.id.dialog_username);
        dialog_pwd = inflate.findViewById(R.id.dialog_pwd);
        dialog_denglu = inflate.findViewById(R.id.dialog_denglu);
        dialog_setting = inflate.findViewById(R.id.dialog_setting);

        dialog_denglu.setOnClickListener(this);
        dialog_setting.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dialog_denglu:
                //子线程 - 网络请求  加权限
                //从文件中获取用户名和密码
                username_str = dialog_username.getText().toString();
                pws_str = dialog_pwd.getText().toString();

                new Thread() {
                    @Override
                    public void run() {
                        try {//捕获异常

                            //从文件中获取ip地址和端口
                            ip = config.getString(XindaluConfig.setting_ed_ip, "");
                            port = config.getString(XindaluConfig.setting_ed_port, "80");
                            //拼接字符串
                            String url = "http://" + ip + ":" + port + "/Users/Login";

                            //上传用户名和密码
                            JSONObject jsonObject = new JSONObject();

                            jsonObject.put("Account", username_str);
                            jsonObject.put("Password", pws_str);
                            jsonObject.put("IsRememberMe", true);
                            //转换成字符串
                            String reqData = jsonObject.toString();
                            //使用网络请求，将账户，密码发送至服务器
                            String resData = HttpMethodUtil.doPost(url, reqData,null);
                            //打印服务器返回的json对象
                            Log.i("登录相应信息", resData);

                            //解析json对象，
                            JSONObject resDatajson = new JSONObject(resData);
                            //获取登录状态，进行状态判断
                            int status = resDatajson.getInt("Status");
                            if (status == 0) {
                                //解析正确的数据
                                JSONObject resultObj = resDatajson.getJSONObject("ResultObj");
                                String accessToken = resultObj.getString("AccessToken");
                                //保存起来
                                SharedPreferences.Editor edit = config.edit();
                                edit.putString(XindaluConfig.Tonken, accessToken);
                                edit.commit();

                                dialog.cancel();
                                //关闭弹出框
                            } else if (status == 1) {
                                //不解析
                                Log.e("不解析", "错误");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e("网络请求", "出错了");
                        }
                    }
                }.start();

                break;
            case R.id.dialog_setting:
                //跳到设置界面
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.main_tv_shezhi:
                //弹框
                Intent intent1 = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent1);
                break;
            case R.id.main_tv_zhuxiao:

                SharedPreferences.Editor edit = config.edit();
                edit.remove(XindaluConfig.Tonken);
                edit.commit();

                tankuang();
                break;
            case R.id.main_but_open:
                main_but_open.setEnabled(false);
                main_but_close.setEnabled(true);
                main_flag = true;
                break;
            case R.id.main_but_close:
                main_but_open.setEnabled(true);
                main_but_close.setEnabled(false);
                main_flag = false;
                break;

        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {
        if(main_flag){

        }else{
            new Thread(){
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                        if(b){
                            new Thread(){
                                @Override
                                public void run() {
                                    String fs_url = "http://"+setting_ed_ip+":"+setting_ed_port+"/Cmds?deviceId="+setting_ed_wangguan+"&apiTag="+setting_ed_fans;
                                    Log.e("风扇url",fs_url);
                                    String fans_res = HttpMethodUtil.doPost(fs_url, "1",tonken);
                                    Log.e("调用风扇接口信息",fans_res);
                                }
                            }.start();
                        }else{
                            new Thread(){
                                @Override
                                public void run() {
                                    String fs_url = "http://"+setting_ed_ip+":"+setting_ed_port+"/Cmds?deviceId="+setting_ed_wangguan+"&apiTag="+setting_ed_fans;
                                    Log.e("风扇url",fs_url);
                                    String fans_res = HttpMethodUtil.doPost(fs_url, "0",tonken);
                                    Log.e("调用风扇接口信息",fans_res);
                                }
                            }.start();
                        }
                    } catch (InterruptedException e) {
                        Log.e("异常退出","异常退出");
                    }
                }
            }.start();
        }
    }

    Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle data = msg.getData();
                    String value = data.getString("value");
                    main_tx_zhi.setText(value);
                    break;
            }
        }
    };
}